import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { fengshuiAnalysis } from '../../services/fengshui';

const FengshuiAnalysis: React.FC = () => {
  const [houseType, setHouseType] = useState('');
  const [direction, setDirection] = useState('');
  const [floor, setFloor] = useState<number | undefined>();
  const [area, setArea] = useState<number | undefined>();
  const [roomCount, setRoomCount] = useState<number | undefined>();
  const [description, setDescription] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  
  // 房屋类型选项
  const houseTypeOptions = [
    { value: 'apartment', label: '公寓' },
    { value: 'house', label: '独栋别墅' },
    { value: 'townhouse', label: '联排别墅' },
    { value: 'villa', label: '别墅' },
    { value: 'office', label: '办公室' },
    { value: 'shop', label: '商铺' },
  ];
  
  // 朝向选项
  const directionOptions = [
    { value: 'north', label: '北' },
    { value: 'northeast', label: '东北' },
    { value: 'east', label: '东' },
    { value: 'southeast', label: '东南' },
    { value: 'south', label: '南' },
    { value: 'southwest', label: '西南' },
    { value: 'west', label: '西' },
    { value: 'northwest', label: '西北' },
  ];
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!houseType || !direction) {
      setError('请选择房屋类型和朝向');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      // 调用风水分析API
      const response = await fengshuiAnalysis({
        houseType,
        direction,
        floor,
        area,
        roomCount,
        description: description || undefined
      });
      
      if (response.code === 200) {
        // 分析成功，跳转到详情页
        navigate(`/fengshui/${response.data.fengshuiId}`);
      } else {
        setError(response.message || '分析失败');
      }
    } catch (err: any) {
      setError(err.message || '分析失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl p-6">
        <div className="text-center mb-8">
          <h2 className="text-2xl font-bold text-gray-900">风水住宅分析</h2>
          <p className="mt-2 text-sm text-gray-600">
            请输入您的房屋信息，获取专业的风水分析
          </p>
        </div>
        
        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label htmlFor="houseType" className="block text-sm font-medium text-gray-700">
              房屋类型 *
            </label>
            <select
              id="houseType"
              className="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              value={houseType}
              onChange={(e) => setHouseType(e.target.value)}
              required
            >
              <option value="">请选择房屋类型</option>
              {houseTypeOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
          </div>
          
          <div>
            <label htmlFor="direction" className="block text-sm font-medium text-gray-700">
              房屋朝向 *
            </label>
            <select
              id="direction"
              className="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              value={direction}
              onChange={(e) => setDirection(e.target.value)}
              required
            >
              <option value="">请选择房屋朝向</option>
              {directionOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
          </div>
          
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label htmlFor="floor" className="block text-sm font-medium text-gray-700">
                楼层
              </label>
              <input
                type="number"
                id="floor"
                min="1"
                className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={floor || ''}
                onChange={(e) => setFloor(e.target.value ? parseInt(e.target.value) : undefined)}
              />
            </div>
            
            <div>
              <label htmlFor="area" className="block text-sm font-medium text-gray-700">
                面积（平方米）
              </label>
              <input
                type="number"
                id="area"
                min="1"
                className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={area || ''}
                onChange={(e) => setArea(e.target.value ? parseInt(e.target.value) : undefined)}
              />
            </div>
          </div>
          
          <div>
            <label htmlFor="roomCount" className="block text-sm font-medium text-gray-700">
              房间数量
            </label>
            <input
              type="number"
              id="roomCount"
              min="1"
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              value={roomCount || ''}
              onChange={(e) => setRoomCount(e.target.value ? parseInt(e.target.value) : undefined)}
            />
          </div>
          
          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700">
              房屋描述（可选）
            </label>
            <textarea
              id="description"
              rows={4}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="请描述房屋结构、布局、家具摆放等信息，越详细分析越准确"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            ></textarea>
          </div>
          
          {error && (
            <div className="text-red-500 text-sm text-center">
              {error}
            </div>
          )}
          
          <div>
            <button
              type="submit"
              disabled={loading}
              className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
            >
              {loading ? '分析中...' : '开始分析'}
            </button>
          </div>
          
          <div className="text-xs text-gray-500 text-center">
            注：未登录用户每次分析需支付1.1元，登录用户0.1元/次，VIP会员无限使用
          </div>
        </form>
      </div>
    </div>
  );
};

export default FengshuiAnalysis;
